package com.example.demo.util;

import com.example.demo.beans.Result;
import com.example.demo.beans.entity.ImmeUser;
import lombok.extern.log4j.Log4j2;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@Log4j2
public class CommUtil {
    public static boolean isListNotBlank(List list){
        return list != null && list.size() > 0;
    }

    /**
     * 校验是否登录
     * @param request
     * @return
     */
    public static boolean checkSession(HttpServletRequest request){
        if(request == null){
            return false;
        }

        ImmeUser user = (ImmeUser) request.getSession().getAttribute(Constant.KEY_CURRENTUSER);
        if(user == null){
            return false;
        }

        return true;
    }

    /**
     * 响应数据
     * @param response
     * @param result
     */
    public static void responseData(HttpServletResponse response, Result result){
        try{
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(result.toString());
            writer.close();

        }catch (Exception e){
            log.error("",e);
        }
    }

    /**
     * 校验忽略的url
     * @param request
     * @param ignoreUrl
     * @return
     */
    public static boolean checkIgnoreUrl(HttpServletRequest request,String ignoreUrl){
        try{
            if(StringUtil.isBlank(ignoreUrl)){
                return false;
            }
            String reqUrl = request.getRequestURI();
            String[] ignoreUrlArr = ignoreUrl.split(",");
            for(String url : ignoreUrlArr){
                if(reqUrl.equals(url)){
                    return true;
                }
            }
        }catch (Exception e){
            log.error("",e);
        }

        return false;

    }

    public static Integer safeToInteger(Object value, Integer dv){
        try {
            if(value != null){
                return Integer.parseInt(String.valueOf(value));
            }
        }catch (Exception e){

        }

        return dv;
    }

    /**
     * 读取文件内容
     * @param path
     * @return
     */
    public static String getContent(String path){
        StringBuilder result = new StringBuilder();
        try{
            FileInputStream fis = new FileInputStream(path);

            BufferedReader br = new BufferedReader(new InputStreamReader(fis, "utf-8"));//构造一个BufferedReader类来读取文件
            String s = null;
            while((s = br.readLine())!=null){//使用readLine方法，一次读一行
                result.append(System.lineSeparator()+s);
            }
            br.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        return result.toString();
    }
}
